package com.fl.nj.controller;

import com.fl.nj.entity.DatabaseConfig;
import com.fl.nj.entity.TableColumn;
import com.fl.nj.entity.TableSchema;
import com.fl.nj.service.DatabaseConfigService;
import com.fl.nj.service.TableColumnService;
import com.fl.nj.service.TableSchemaService;
import com.fl.nj.util.SchemaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库模式Controller
 * 提供RESTful API接口，用于获取和管理数据库表结构和字段信息
 */
@RestController
@RequestMapping("/api/schema")
public class SchemaController {
    @Autowired
    private DatabaseConfigService databaseConfigService;
    
    @Autowired
    private TableSchemaService tableSchemaService;
    
    @Autowired
    private TableColumnService tableColumnService;

    /**
     * 获取指定数据库配置的所有表名
     * @param dbConfigId 数据库配置ID
     * @return 表名列表
     */
    @GetMapping("/tables/{dbConfigId}")
    public ResponseEntity<Map<String, Object>> getTables(@PathVariable Long dbConfigId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 获取表名列表
            List<String> tableNames = SchemaUtil.getAllTableNames(dbConfig);
            result.put("success", true);
            result.put("data", tableNames);
            return ResponseEntity.ok(result);
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "获取表列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取指定数据库配置中指定表的字段信息
     * @param dbConfigId 数据库配置ID
     * @param tableName 表名
     * @return 表字段信息列表
     */
    @GetMapping("/columns/{dbConfigId}/{tableName}")
    public ResponseEntity<Map<String, Object>> getTableColumns(
            @PathVariable Long dbConfigId, 
            @PathVariable String tableName) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 获取表字段信息
            List<TableColumn> columns = SchemaUtil.getTableColumns(dbConfig, tableName);
            result.put("success", true);
            result.put("data", columns);
            return ResponseEntity.ok(result);
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "获取表字段信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取指定数据库配置中指定表的表结构信息
     * @param dbConfigId 数据库配置ID
     * @param tableName 表名
     * @return 表结构信息
     */
    @GetMapping("/table/{dbConfigId}/{tableName}")
    public ResponseEntity<Map<String, Object>> getTableSchema(
            @PathVariable Long dbConfigId, 
            @PathVariable String tableName) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 获取表结构信息
            TableSchema schema = SchemaUtil.getTableSchema(dbConfig, tableName);
            if (schema == null) {
                result.put("success", false);
                result.put("message", "表不存在: " + tableName);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 获取表字段信息
            List<TableColumn> columns = SchemaUtil.getTableColumns(dbConfig, tableName);
            
            result.put("success", true);
            result.put("schema", schema);
            result.put("columns", columns);
            return ResponseEntity.ok(result);
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "获取表结构信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据数据库配置获取表结构并保存到数据库
     * @param request 请求参数，包含数据库配置ID和表名
     * @return 保存结果
     */
    @PostMapping("/save-table")
    public ResponseEntity<Map<String, Object>> saveTable(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取请求参数
            Long dbConfigId = Long.parseLong(request.get("dbConfigId").toString());
            String tableName = request.get("tableName").toString();
            
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 检查表结构是否已存在
            TableSchema existingSchema = tableSchemaService.getByDbConfigIdAndTableName(dbConfigId, tableName);
            if (existingSchema != null) {
                // 如果已存在，则先删除旧的字段信息
                tableColumnService.deleteBySchemaId(existingSchema.getId());
            }
            
            // 获取并保存表结构信息
            TableSchema schema = SchemaUtil.getTableSchema(dbConfig, tableName);
            if (schema == null) {
                result.put("success", false);
                result.put("message", "表不存在: " + tableName);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            schema.setDbConfigId(dbConfigId);
            
            if (existingSchema != null) {
                // 更新现有表结构
                schema.setId(existingSchema.getId());
                tableSchemaService.update(schema);
            } else {
                // 保存新表结构
                tableSchemaService.save(schema);
            }
            
            // 获取并保存表字段信息
            List<TableColumn> columns = SchemaUtil.getTableColumns(dbConfig, tableName);
            for (TableColumn column : columns) {
                column.setSchemaId(schema.getId());
            }
            tableColumnService.batchSave(columns);
            
            result.put("success", true);
            result.put("message", "表结构信息保存成功");
            result.put("data", schema);
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "参数格式错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "获取表结构信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        } catch (RuntimeException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据数据库配置批量获取表结构并保存到数据库
     * @param request 请求参数，包含数据库配置ID
     * @return 保存结果
     */
    @PostMapping("/batch-save-tables")
    public ResponseEntity<Map<String, Object>> batchSaveTables(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取请求参数
            Long dbConfigId = Long.parseLong(request.get("dbConfigId").toString());
            
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 获取所有表名
            List<String> tableNames = SchemaUtil.getAllTableNames(dbConfig);
            int successCount = 0;
            int failCount = 0;
            
            // 批量保存表结构信息
            for (String tableName : tableNames) {
                try {
                    // 检查表结构是否已存在
                    TableSchema existingSchema = tableSchemaService.getByDbConfigIdAndTableName(dbConfigId, tableName);
                    if (existingSchema != null) {
                        // 如果已存在，则先删除旧的字段信息
                        tableColumnService.deleteBySchemaId(existingSchema.getId());
                    }
                    
                    // 获取并保存表结构信息
                    TableSchema schema = SchemaUtil.getTableSchema(dbConfig, tableName);
                    if (schema != null) {
                        schema.setDbConfigId(dbConfigId);
                        
                        if (existingSchema != null) {
                            // 更新现有表结构
                            schema.setId(existingSchema.getId());
                            tableSchemaService.update(schema);
                        } else {
                            // 保存新表结构
                            tableSchemaService.save(schema);
                        }
                        
                        // 获取并保存表字段信息
                        List<TableColumn> columns = SchemaUtil.getTableColumns(dbConfig, tableName);
                        for (TableColumn column : columns) {
                            column.setSchemaId(schema.getId());
                        }
                        tableColumnService.batchSave(columns);
                        
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    System.err.println("保存表结构信息失败 (" + tableName + "): " + e.getMessage());
                    failCount++;
                }
            }
            
            result.put("success", true);
            result.put("message", "批量保存表结构信息完成");
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalCount", tableNames.size());
            return ResponseEntity.status(HttpStatus.CREATED).body(result);
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "参数格式错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "获取表列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        } catch (RuntimeException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}